package com.zte.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zte.sys.login.model.LUsers;
import com.zte.util.LogOutException;
import com.zte.util.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String userId =(String) session.getAttribute("id");
        if(userId==null){
//            ResultMessage rm = new ResultMessage();
//            rm.setStatus(500);
//            rm.setFlag(false);
//            rm.setMsg("未登录！");
//
//            ObjectMapper m = new ObjectMapper();
//            String json = m.writeValueAsString(rm);
//
//            response.setContentType("application/json;charset=utf8");
//
//            response.getWriter().write(json);
            throw new LogOutException("未登录，请先登录");
        }
        LUsers user =(LUsers) redisTemplate.opsForValue().get(userId);
        if(user!=null){
            redisTemplate.opsForValue().set(userId,user,30, TimeUnit.MINUTES);
            return true;
        }else{
            ResultMessage rm = new ResultMessage();
            rm.setStatus(500);
            rm.setFlag(false);
            rm.setMsg("未登录！");

            ObjectMapper m = new ObjectMapper();
            String json = m.writeValueAsString(rm);

            response.setContentType("application/json;charset=utf8");

            response.getWriter().write(json);
            throw new LogOutException("未登录，请先登录");
        }

    }

}
